//--
//-- RGB colour object
//--

// Construct an RGB colour object from a '#rrggbb', '#rgb' or 'rgb(n,n,n)' string or from separate r,g,b values
function RGB(r, g, b)
{
	this.r = 0;
	this.g = 0;
	this.b = 0;
	if(typeof r == "string") {
		if(r.substr(0, 1) == "#") {
			if(r.length == 7) {
				this.r = parseInt(r.substr(1, 2), 16) / 255;
				this.g = parseInt(r.substr(3, 2), 16) / 255;
				this.b = parseInt(r.substr(5, 2), 16) / 255;
			} else {
				this.r = parseInt(r.substr(1, 1), 16) / 15;
				this.g = parseInt(r.substr(2, 1), 16) / 15;
				this.b = parseInt(r.substr(3, 1), 16) / 15;
			}
		} else {
			var rgbPattern = /rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/;
			var c = r.match(rgbPattern);
			if(c) {
				this.r = parseInt(c[1], 10) / 255;
				this.g = parseInt(c[2], 10) / 255;
				this.b = parseInt(c[3], 10) / 255;
			}
		}
	} else {
		this.r = r;
		this.g = g;
		this.b = b;
	}
	return this;
}

// Mixes this colour with another in a specified proportion
// c = other colour to mix
// f = 0..1 where 0 is this colour and 1 is the new colour
// Returns an RGB object
RGB.prototype.mix = function(c, f)
{
	return new RGB(this.r + (c.r - this.r) * f, this.g + (c.g - this.g) * f, this.b + (c.b - this.b) * f);
};

// Return an rgb colour as a #rrggbb format hex string
RGB.prototype.toString = function()
{
	var to255Range = function(value) {
		var clamped = value < 0 ? 0 : value > 1 ? 1 : value;
		return clamped * 255;
	};

	var to2DigitString = function(value) {
		var s = Math.floor(value).toString(16);
		return ("0" + s).slice(-2);
	};

	return "#" +
		to2DigitString(to255Range(this.r)) +
		to2DigitString(to255Range(this.g)) +
		to2DigitString(to255Range(this.b));
};

